package com.yxhl.zoume.core.main.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.activity.base.BaseActivityWithToolBar;
import com.yxhl.zoume.common.ui.view.MobileDialView;
import com.yxhl.zoume.core.func.push.info.PushActionType;
import com.yxhl.zoume.core.func.push.model.PushMessage;
import com.yxhl.zoume.core.main.info.EnableUpdateApp;
import com.yxhl.zoume.core.main.info.MainEntrance;
import com.yxhl.zoume.core.main.model.MainEntranceInfo;
import com.yxhl.zoume.core.main.presenter.CheckAppUpdatePresenter;
import com.yxhl.zoume.core.main.ui.Fragment.UpdateAppDialogFragment;
import com.yxhl.zoume.core.main.ui.event.UpdateAppEvent;
import com.yxhl.zoume.core.main.ui.view.MainView;
import com.yxhl.zoume.core.specialcar.model.SpecialCarContainerActivityParam;
import com.yxhl.zoume.core.specialcar.model.SpecialCarContainerEntrance;
import com.yxhl.zoume.data.http.rest.response.login.CheckUpdateResponse;
import com.yxhl.zoume.di.component.updateapp.DaggerUpdateAppComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.ActivityControlUtils;
import com.yxhl.zoume.utils.DensityUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Xboy on 16/3/16.
 */
public class MainActivity extends BaseActivityWithToolBar implements MainView {

    private static final String TAG = "MainActivity";

    @BindView(R.id.tabhost)
    public ZMFragmentTabHost tabHost;


    //arguments
    @Inject
    CheckAppUpdatePresenter mCheckAppUpdatePresenter;

    private boolean checkLocationPermission;
    /**
     * 快车页面传入参数
     */
    private SpecialCarContainerActivityParam mSpecialCarActivityParam;

    /**
     * 推送消息
     */
    private MainEntranceInfo mMainEntranceInfo;

    private CompositeSubscription mMainCompositeSubscription;
    private UpdateAppDialogFragment mUpdateAppDialogFragment;

    public static Intent getCallingIntent(Activity activity) {
        Intent launch = new Intent(activity, MainActivity.class);
        return launch;
    }

    /**
     * App 处于进程时,获取跳转到MainActivity的Intent
     *
     * @param activity
     * @param entranceInfo
     * @return
     */
    public static Intent getCallingIntent(Activity activity, MainEntranceInfo entranceInfo) {
        Intent launch = new Intent(activity, MainActivity.class);
        launch.putExtra(UIConstants.HomePage.INTENT_KEY_HOME_PAGE_ENTRANCE, entranceInfo);
        return launch;
    }

    /**
     * 推送 跳转
     *
     * @param context
     * @param entranceInfo
     * @return
     */
    public static Intent getPushIntent(Context context, MainEntranceInfo entranceInfo) {
        Intent launch = new Intent(context, MainActivity.class);
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        launch.putExtra(UIConstants.HomePage.INTENT_KEY_HOME_PAGE_ENTRANCE, entranceInfo);
        return launch;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LOG.e(TAG, "onCreate");
        handleIntent();
        initializeHandle();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LOG.e(TAG, "onNewIntent");
        setIntent(intent);
        handleIntent();
        initializeHandle();
    }

    private void initializeHandle() {
        LOG.e(TAG, "onStart");
        hideLeftIcon();
        ActivityControlUtils.put(this);
        mCheckAppUpdatePresenter.attachView(this);
        onRxBusEvent();
        mCheckAppUpdatePresenter.checkAppUpdate();
        // 构建tabhost
        setupTabHost();
        handleEntranceInfo();
    }

    private void handleIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mMainEntranceInfo = (MainEntranceInfo) intent.getSerializableExtra(UIConstants.HomePage.INTENT_KEY_HOME_PAGE_ENTRANCE);
        }
    }

    /**
     * 如果有推送信息,处理推送信息
     */
    private void handleEntranceInfo() {
        if (mMainEntranceInfo != null) {
            MainEntrance mainEntrance = mMainEntranceInfo.getMainEntrance();
            Map entranceMap = mMainEntranceInfo.getEntranceMap();
            switch (mainEntrance) {
                case PUSH:
                    if (entranceMap.containsKey(mainEntrance)) {
                        PushMessage pushMessage = (PushMessage) entranceMap.get(mainEntrance);
                        String action = pushMessage.getAction();
                        switch (action) {
                            case PushActionType.SPECIAL_CAR_SCHEDULE_MAP:
                                String orderId = pushMessage.getId();
                                navigateToSpecialCarContainerActivity(new SpecialCarContainerActivityParam(
                                        SpecialCarContainerEntrance.SCHEDULE_MAP_FROM_PUSH,
                                        orderId
                                ));
                                break;
                            case PushActionType.TRIP_DETAIL:
                                getAppComponent().navigator().navigateToDetailTripContainerActivity(this, pushMessage);
                                break;
                        }
                        break;
                    }
            }
        }
    }

    private void setupTabHost() {
        // 配置tabhost
        tabHost.setup(this, getSupportFragmentManager(), R.id.main_tab_content);
        if (10 < android.os.Build.VERSION.SDK_INT) {// 不带分割线
            tabHost.getTabWidget().setShowDividers(0);
        }
        // 初始化底部tab
        initTabs();

        tabHost.setCurrentTab(getCurrentTabOrder());
    }

    /**
     * @return 当前需要显示的tab序号
     */
    private int getCurrentTabOrder() {
        int currentTabOrder = 0;
        if (mMainEntranceInfo != null) {
            MainEntrance mainEntrance = mMainEntranceInfo.getMainEntrance();
            Map entranceMap = mMainEntranceInfo.getEntranceMap();
            switch (mainEntrance) {
                case PUSH:
                    if (entranceMap.containsKey(mainEntrance)) {
                        PushMessage pushMessage = (PushMessage) entranceMap.get(mainEntrance);
                        String action = pushMessage.getAction();
                        switch (action) {
                            case PushActionType.OPEN_APP:
                                currentTabOrder = 0;
                                break;
                            case PushActionType.SPECIAL_CAR_SCHEDULE_MAP:
                                currentTabOrder = 1;
                                break;
                            case PushActionType.CURRENT_TRIP:
                            case PushActionType.TRIP_DETAIL:
                                currentTabOrder = 2;
                                break;
                        }
                    }
                    break;
                case PAYMENT:
                    currentTabOrder = 2;
                    break;
                case SPLASH:
                    currentTabOrder = 0;
                    break;
            }

        }
        return currentTabOrder;
    }

    private void initTabs() {
        TabWidget tabWidget = tabHost.getTabWidget();
        if (tabWidget != null) {
            int tabCount = tabWidget.getChildCount();
            MainTab[] tabs = MainTab.values();
            if (tabCount >= tabs.length) {
                return;
            }
        }

        MainTab[] tabs = MainTab.values();
        final int size = tabs.length;// tab数目

        for (int i = 0; i < size; i++) {

            // 配置tab
            MainTab mainTab = tabs[i];
            TabHost.TabSpec tab = tabHost.newTabSpec(getString(mainTab.getResName()));
            View indicator = LayoutInflater.from(getApplicationContext()).inflate(R.layout.main_tab_indicator, null);
            TextView tabTitle = (TextView) indicator.findViewById(R.id.tab_title);
            Drawable drawable = this.getResources().getDrawable(mainTab.getResIcon());
            tabTitle.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);//设置icon
            tabTitle.setPadding(0, DensityUtils.dip2px(this,3),0,0);
            tabTitle.setText(getString(mainTab.getResName()));//设置标题
            tab.setIndicator(indicator);

            // 设置tabcontent
            tab.setContent(new TabHost.TabContentFactory() {
                @Override
                public View createTabContent(String tag) {
                    return new View(MainActivity.this);
                }
            });

            // 添加tab
            tabHost.addTab(tab, mainTab.getCls(), null);

        }

    }

    private Fragment getCurrentFragment() {
        return getSupportFragmentManager().findFragmentByTag(
                tabHost.getCurrentTabTag());
    }

    /**
     * 处理推送消息,跳转到包车出行/拼车行程地图页面
     * Ethan
     *
     * @param activityParam
     */
    public void navigateToSpecialCarContainerActivity(SpecialCarContainerActivityParam activityParam) {
        checkLocationPermission = PermissionHelper.checkLocationPermission(this);
        if (checkLocationPermission) {
            getAppComponent().navigator().navigateToSpecialCarContainerActivity(this, activityParam);
        } else {
            mSpecialCarActivityParam = activityParam;
            PermissionHelper.takeLocationPermission(this, PermissionHelper.REQUEST_CODE_SCHEDULE_MAP_LOCATION);
        }
    }

    /**
     * RxBus 点击包车出行/预约快车 网络请求获取到订单ID后的回调
     */
    public void onRxBusEvent() {
        mMainCompositeSubscription = new CompositeSubscription();

        mMainCompositeSubscription.add(toSubscription(UpdateAppEvent.class,
                new Action1<UpdateAppEvent>() {
                    @Override
                    public void call(UpdateAppEvent updateAppEvent) {
                        PermissionHelper.takeWriteExternalStoragePermission(MainActivity.this);
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                }
        ));
    }


    @Override
    public void renderUpdateAppVersionDataOnSuccess(CheckUpdateResponse response) {

        String updateType = response.getIsNeedUpdate();
        switch (updateType) {
            case EnableUpdateApp.UPDATE:
                mUpdateAppDialogFragment = UpdateAppDialogFragment.newInstance(response);
                mUpdateAppDialogFragment.show(
                        getSupportFragmentManager(),
                        mUpdateAppDialogFragment.getClass().getSimpleName()
                );
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length >= 1) {
            switch (requestCode) {
                case PermissionHelper.REQUEST_CODE_CALL_USER_CENTER:
                    //获取到了拨打电话权限
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if (getCurrentFragment() instanceof MobileDialView) {
                            ((MobileDialView) getCurrentFragment()).dial();
                        }
                    } else {
                        PromptUtils.showShort(this, getString(R.string.permission_telephone_deny_message));
                    }
                    break;
                //推送快车行程地图
                case PermissionHelper.REQUEST_CODE_SCHEDULE_MAP_LOCATION:
                    //判断用户是或同意了授权
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        getAppComponent().navigator().navigateToSpecialCarContainerActivity(this, mSpecialCarActivityParam);
                    } else {
                        PromptUtils.showShort(this, getString(R.string.permission_location_deny_message));
                    }
                    break;
                //App版本更新
                case PermissionHelper.REQUEST_CODE_WRITE_EXTERNAL_STORAGE:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if (mUpdateAppDialogFragment != null) {
                            mUpdateAppDialogFragment.startUpdateAppService(this);
                        }
                    } else {
                        PromptUtils.showShort(this, getString(R.string.permission_write_external_storage_deny_message));
                    }
                    break;

            }
        }
    }

    @Override
    protected void onDestroy() {
        LOG.e(TAG, "onDestroy");
        ActivityControlUtils.remove(this);
        mMainCompositeSubscription.unsubscribe();
        mMainCompositeSubscription = null;
        mCheckAppUpdatePresenter.onDestroy();
        super.onDestroy();
    }


    @Override
    protected void onHeaderRightClick(View view) {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.main_activity;
    }

    @Override
    protected void initializeInjector() {
        DaggerUpdateAppComponent
                .builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onHeaderLeftClick(View view) {
    }
}

